package com.caration.shell.config;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

import android.content.Context;
import android.os.Environment;

import com.caration.shell.AlertHelper;
import com.caration.shell.Home;
import com.caration.shell.R;
import com.caration.shell.ShellProvider;
import com.caration.shell.cr3d.SharedData;

public final class ConfigManger {

	public static final String DB_INTERNAL_PATH = Environment
			.getDataDirectory()
			+ "/data/"
			+ SharedData.getContext().getPackageName()
			+ "/databases/"
			+ ShellProvider.DATABASE_NAME;

	public static final String DB_EXTENAL_PATH = Environment
			.getExternalStorageDirectory() + "crshell_backup.db";

	public static final String CONFIG_INTERNAL_PATH = Environment
			.getDataDirectory()
			+ "/data/"
			+ SharedData.getContext().getPackageName()
			+ "/shared_prefs/config.xml";

	public static final String CONFIG_EXTENAL_PATH = Environment
			.getExternalStorageDirectory() + "crshell_settings.xml";

	/**
	 * Clear all data
	 */
	public static void clearAll() {
		CompatibilityConfig.clear();
		CommonConfig.clear();
		File dbFile = new File(DB_INTERNAL_PATH);
		if (dbFile.exists())
			dbFile.delete();
	}

	public static void showImportDialog(final Context context) {
		AlertHelper.showDialog(R.string.message_dialog_import_config,
				new Runnable() {
					@Override
					public void run() {
						new ImportAyncTask(context).execute(null);
					}
				});
	}

	static void transferFile(File fromFile, File toFile) {
		FileChannel from = null;
		FileChannel target = null;
		try {
			from = (new FileInputStream(fromFile)).getChannel();
			target = (new FileOutputStream(toFile)).getChannel();
			from.transferTo(0L, from.size(), target);
		} catch (IOException e) {
		} finally {
			try {
				if (from != null)
					from.close();
				if (target != null)
					target.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}

	public static void showExportDialog(final Context context) {
		AlertHelper.showDialog(R.string.message_dialog_export_config,
				new Runnable() {
					@Override
					public void run() {
						new ExportAsyncTask(context).execute(null);
					}
				});
	}

	public static void showResetDialog() {
		AlertHelper.showDialog(R.string.pref_title_shell_reset, new Runnable() {

			@Override
			public void run() {
				clearAll();
				Home.getInstance().restartDelayed();
			}
		});
	}

}
